package com.oxchinx.order.service.Impl;

import com.oxchinx.order.client.ProductClient;
import com.oxchinx.order.dao.OrderDetailRepository;
import com.oxchinx.order.dao.OrderMasterRepository;
import com.oxchinx.order.dto.CartDTO;
import com.oxchinx.order.dto.OrderDTO;
import com.oxchinx.order.model.OrderDetail;
import com.oxchinx.order.model.OrderMaster;
import com.oxchinx.order.model.ProductInfo;
import com.oxchinx.order.model.enums.OrderStatusEnum;
import com.oxchinx.order.model.enums.PayStatusEnum;
import com.oxchinx.order.service.OrderService;
import com.oxchinx.order.utils.OidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by dell on 2018/5/23.
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private ProductClient productClient;

    @Override
    public OrderDTO create(OrderDTO orderDTO) {
       String orderId = OidUtil.newId();
         //todo  查询商品信息（条用商品服务）
        List<String> productIdList = orderDTO.getOrderDetailList().stream().map(OrderDetail::getProductId)
                .collect(Collectors.toList());
        List<ProductInfo> productInfoList = productClient.listForOrder(productIdList);

         //todo  计算总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        for(OrderDetail orderDetail:orderDTO.getOrderDetailList()){
            for(ProductInfo productInfo:productInfoList){
                //单价*数量
                orderAmount = productInfo.getProductPrice().
                        multiply(new BigDecimal(orderDetail.getProductQuantity())).
                        add(orderAmount);

                BeanUtils.copyProperties(productInfo,orderDetail);
                orderDetail.setOrderId(orderId);
                orderDetail.setDetailId(OidUtil.newId());

                //订单详情入库
                orderDetailRepository.save(orderDetail);
            }
        }

         //todo  扣库存（调用商品服务）
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().
                map(e -> new CartDTO(e.getProductId(),e.getProductQuantity())).
                collect(Collectors.toList());
        productClient.decreaseStock(cartDTOList);


         //  订单入库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(OidUtil.newId());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());

        orderMasterRepository.save(orderMaster);
        return orderDTO;
    }
}
